import './LoginPage.scss'
import { Link, useNavigate } from 'react-router-dom';
import { Form, Button, Input } from "antd";
import { useDispatch } from 'react-redux';
import { loginAPI } from '@/apis/user';
import { fetchLogin, setUserStatus } from '@/store/modules/user';
import { useSelector } from 'react-redux';
import { useEffect } from 'react';
import { message } from 'antd';


function LoginPage() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { user_status } = useSelector(state => state.user);

  const login = async (value) => {

    const res = await loginAPI({
      telephone: value.phone,
      userpassword: value.password
    })

    if (res.data.success) {
      message.success(res.data.message);
      dispatch(setUserStatus({
        user_role: res.data.role,
        token: res.data.token
      }))
    } else {
      message.error(res.data.message);
    }

    console.log(res.data);
    if (res.data.token) navigate("/" + res.data.role);

  }

  return (
    <div className="LoginPage">
      <Form
        id='log-form-place'
        name='logform'
        layout='horizontal'
        onFinish={login}
        validateTrigger="onBlur"
        labelCol={
          {
            span: 7
          }
        }
        wrapperCol={
          {
            span: 12
          }
        }
      >
        <header className='log-form-header'>
          讯飞教育用户登录
        </header>
        <Form.Item
          label="电话号码"
          name="phone"
          rules={[
            {
              required: true,
              message: '请填写您的电话号码',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: '请输入您的密码',
            },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          wrapperCol={
            {
              offset: 9
            }
          }
        >
          <Button
            className='log-btn'
            type="primary"
            htmlType='submit'
          >
            登录
          </Button>
        </Form.Item>
        <Link to={'/register'} id='log-to-reg'>还没有账号？点此注册</Link>
      </Form>
    </div>
  );
}

export default LoginPage;